<?php
/**
 * 部分PC端需调用 e驾优选API
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/25/025
 * Time: 上午 11:39
 */
namespace app\service;


use think\Exception;

class RpcClient
{
    private $debug;
    private $url;

    /**
     * @param $url
     * @param bool $debug
     */
    public function __construct($url,$debug = false) {
        $this->url = $url;
        empty($debug) ? $this->debug = false : $this->debug = true;
    }

    /**
     * @param $method
     * @param $params
     * @return bool
     * @throws Exception
     */
    public function __call($method,$params) {
        // 检验request信息
        if (!is_scalar($method))    throw new Exception('Method name has no scalar value');

        if (is_array($params)) {
            $params = array_values($params);
        } else {
            throw new Exception('Params must be given as array');
        }

        // 拼装成一个request请求
        $request = array('method' => $method, 'params' => $params);

        $request = json_encode($request);
        $this->debug && $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n";
        $opts = array (
            'http' => array (
                'method'  => 'POST',
                'header'  => 'Content-type: application/json',
                'content' => $request
            )
        );

        $context = stream_context_create($opts);
        if ($result = file_get_contents($this->url, false, $context)) {
            $response = json_decode($result, true);
        } else {
            throw new Exception('Unable to connect to '.$this->url);
        }

        // 输出调试信息
        if ($this->debug) {
            echo nl2br(($this->debug));
        }

        if (!is_null($response['error'])) {
            throw new Exception('Request error: '.$response['error']);
        }

        return $response['result'];
    }
}